package cn.edu.ctbu.gudie.restcontroller;

import cn.edu.ctbu.gudie.domain.Patient;
import cn.edu.ctbu.gudie.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/webapi/login")
public class LoginRestController{
    @Autowired
    PatientService patientService;
    /**
     * 登录
     *
     * @param httpRequest
     * @param loginRequest
     * @return
     */
    @PostMapping("/patient")
    public int student(HttpServletRequest httpRequest, @RequestBody LoginRequest loginRequest) {
        // 判断用户名和密码是否存在
        List<Patient> students = patientService.findByPatientNameAndPatientPassword(loginRequest.getName(), loginRequest.getPassword());
        // 如果存在，写入session
        if (students.size() > 0) {
            HttpSession session = httpRequest.getSession();
            session.setAttribute("patientid", students.get(0).getId());
            session.setAttribute("patient", students.get(0));
            return 1; // 成功
        } else {
            // 如果不存在，返回出错
            return -1; // 不存在用户
        }
    }
    public static class LoginRequest {
        private String name;
        private String password;

        // getters and setters
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
}
